package com.rd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rd.mapper.MenuRoleMapper;
import com.rd.pojo.AdminRole;
import com.rd.pojo.MenuRole;
import com.rd.service.IAdminRoleService;
import com.rd.service.IMenuRoleService;
import com.rd.util.ResultModel;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author qiufenfen
 * @since 2023-10-26
 */
@Service
public class MenuRoleServiceImpl extends ServiceImpl<MenuRoleMapper, MenuRole> implements IMenuRoleService {

    @Resource
    private MenuRoleMapper menuRoleMapper;


    @Resource
    RedisTemplate redisTemplate;
    @Resource
    IAdminRoleService adminRoleService;
    /**
     * @return
     * @description: 更新角色菜单
     * @param: rid
     * @param: mids
     */
    @Override
    @Transactional
    public ResultModel updateMenuRole(Integer rid, Integer[] mids) {
        // 从中间表 t_menu_role中删除这个角色所对应的所有的权限
        menuRoleMapper.delete(new QueryWrapper<MenuRole>().eq("rid", rid));
        if (null == mids || 0 == mids.length) {
            return ResultModel.createBySuccess("此角色对应的权限更新成功！");
        }
        //再向t_menu_role中添加数据(批量添加)
        Integer result = menuRoleMapper.insertRecord(rid, mids);
        if (result == mids.length) {
            //1.查询这个角色相关的用户  select * from t_admin_role where rid=?
            List<Integer> adminIdList = adminRoleService.list(
                    new QueryWrapper<AdminRole>().eq("rid", rid))
                    .stream().map(ar-> ar.getAdminId())
                    .collect(Collectors.toList());

            //去 t_admin_role表中查询 adminId
            if(Objects.nonNull(adminIdList)){
                for (Integer adminId : adminIdList) {
                    //删除这个用户在redis中存储的权限,需要下一次登录登录的时候从数据库中重新查询
                    Map<String,String> mapFromRedis =
                            redisTemplate.opsForHash().entries("menu_" + adminId);
                    Set<String> set = mapFromRedis.keySet();
                    for (String s : set) {
                        redisTemplate.opsForHash().delete("menu_"+adminId,s);
                    }
                }
            }
            return ResultModel.createBySuccess("此角色对应的权限更新成功！");
        }
        return ResultModel.createBySuccess("此角色对应的权限更新失败！");
    }

}
